package com.sensor.data.assist;

import com.alibaba.fastjson.JSONObject;
import com.sensor.data.dao.SensorToDB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * FileName: ReceiveThread
 * Create by fengzheng on 2019/4/11 10:41
 * Description: 接收数据线程
 */
public class ReceiveThread extends Thread {

    private SensorToDB sensorToDB;
    private int port;

    public ReceiveThread(int port,SensorToDB mSensorToDB) {
        this.port = port;
        this.sensorToDB = mSensorToDB;
    }

    @Override
    public void run() {
        try {
            // 监听端口
            ServerSocket serverSocket = new ServerSocket(port,10);
            Socket socket = serverSocket.accept();
            System.out.println("端口"+port+"建立监听成功");

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));

            while (true){

                // 获取输入流
                /*InputStream inputStream = socket.getInputStream();
                InputStreamReader streamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(streamReader);*/

                // 从Buffer中读取字节
                String readStr = bufferedReader.readLine();
                System.out.println("端口"+port+"===>"+readStr);
                if( !(readStr.equals("")) ){
                    JSONObject jsonObject = JSONObject.parseObject(readStr);

                    String area = "area" + port;
                    long time = System.currentTimeMillis();
                    sensorToDB.insertData(jsonObject.getIntValue("id"),
                            jsonObject.getFloatValue("value"),area,time);
                }

                /*bufferedReader.close();
                streamReader.close();
                inputStream.close();*/
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("端口"+port+"开启监听失败！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常");
        }
    }
}
